/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentResource.file;

import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ContentResourceForm;
import com.blandware.atleap.webapp.form.core.UploadContentResourceForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.ResourceTypesManager;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>Returns page with form to create new file
 * </p>
 * <p><a href="CallCreateFileAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.14 $ $Date: 2008/04/29 17:48:07 $
 * @struts.action name="contentResourceForm"
 * path="/core/contentResource/file/callCreate"
 * validate="false"
 * roles="core-contentResource-create"
 * input="callCreateContentResource"
 * @struts.action-forward name="createFile"
 * path=".core.contentResource.file.create"
 * @struts.action-forward name="callCreateContentResource"
 * path="/core/contentResource/callCreate.do"
 */
public final class CallCreateFileAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();
        UploadContentResourceForm uploadContentResourceForm = (UploadContentResourceForm) session
                .getAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
		if ( uploadContentResourceForm == null || uploadContentResourceForm.getFile() == null ) {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing required attribute in session '" + WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY + "'");
			}
			ActionMessages errors = new ActionMessages();
			errors.add("missingResource", new ActionMessage("core.contentResource.errors.missingResource"));
			saveErrors(request, errors);
			saveToken(request);
			return mapping.findForward("callCreateContentResource");
		}
		FormFile formFile = uploadContentResourceForm.getFile();
		String fileName = formFile.getFileName();

		ContentResourceForm contentResourceForm = (ContentResourceForm) form;

		String uri = "/";
        boolean isUriEmpty = GenericValidator.isBlankOrNull(contentResourceForm.getUri());
        boolean isFolderEmpty = GenericValidator.isBlankOrNull((String) session.getAttribute(WebappConstants.CONTENT_RESOURCES_FOLDER_KEY));
        if (!isFolderEmpty) {
            uri = (String) session.getAttribute(WebappConstants.CONTENT_RESOURCES_FOLDER_KEY);
        } else if ( isUriEmpty && session.getAttribute(WebappConstants.CONTENT_RESOURCES_CURRENT_PATH_KEY) != null ) {
			uri = session.getAttribute(WebappConstants.CONTENT_RESOURCES_CURRENT_PATH_KEY) + "/";
			if ( !uri.endsWith("/") ) {
				uri += "/";
			}
            // TODO: this is a patch!! Fix the reason!
            if (!"/".equals(uri) && !"".equals(uri)) {
                if (!uri.startsWith("/")) {
                    uri = "/" + uri;
                }
            }
		}
		contentResourceForm.setUri(uri + fileName);

		ResourceTypesManager resourceTypesManager = ResourceTypesManager.getInstance(
                session.getServletContext());
		String mimeType = resourceTypesManager.getMimeTypeByFileName(fileName);

		if ( log.isDebugEnabled() ) {
			log.debug("Uploaded formFile resource with mimeType=" + mimeType);
		}
		contentResourceForm.setMimeType(mimeType);
		contentResourceForm.setSize(String.valueOf(formFile.getFileData().length));
		session.setAttribute(WebappConstants.CONTENT_FILE_NEW_FILENAME_KEY, formFile.getFileName());

		// Populate content locale list
		List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();
		session.setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);

        saveToken(request);
		return mapping.findForward("createFile");
	}
}